package cn.yto.print.system.version;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.yto.print.constants.AssistantConstants;
import cn.yto.print.model.dto.KhgjVersionDTO;
import cn.yto.print.model.dto.OperateLogDTO;
import cn.yto.print.utils.HttpRequestUtil;
import cn.yto.print.utils.MachineCodeUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.Preferences;

public class KhgjContactManager {

    private static final Logger logger = LogManager.getLogger(KhgjContactManager.class);

    private static final String SERVER_SYSTEM = "PRTAST";
    private static final String SECRET_KEY = "JhD542hD29da";

    // 版本更新URL、日志上传URL、打印插件下载地址URL
    private static final String VERSION_UPDATE_URL = "https://kh.yto.net.cn/webApi/openApi/platformVersion/checkUpgrade";
    private static final String OPERATE_LOG_URL = "https://kh.yto.net.cn/webApi/openApi/platformVersion/accountLog";
    private static final String PLUGIN_INSTALL_URL = "https://kh.yto.net.cn/webApi/openApi/platformVersion/getPrinterPluginsUrl";

    private static final Preferences PREFS = Preferences.userNodeForPackage(KhgjContactManager.class);

    /**
     * 检查是否有新版本更新
     */
    public static KhgjVersionDTO getVersionUpdate() {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("account", MachineCodeUtil.generateMachineCode());
            params.put("serverSystem", SERVER_SYSTEM);
            params.put("appSystem", "windows");
            params.put("softwareVersion", System.getProperty(AssistantConstants.APP_VERSION));
            String requestStr = JSONUtil.toJsonStr(params);
            logger.info("小助手最新版本信息-接口请求：{}", requestStr);
            String responseStr = sendToKhgj(JSONUtil.toJsonStr(params), VERSION_UPDATE_URL);
            logger.info("小助手最新版本信息-接口响应：{}", responseStr);
            if (!StringUtils.isEmpty(responseStr)) {
                Map<String, Object> responseMap = JSONUtil.toBean(responseStr, Map.class);
                String dataStr = MapUtil.getStr(responseMap, "data");
                return JSONUtil.toBean(dataStr, KhgjVersionDTO.class);
            }
            return null;
        } catch (Exception e) {
            logger.error("小助手最新版本信息-接口异常", e);
            return null;
        }
    }

    /**
     * 记录第一次操作日志
     */
    public static void firstLogOperate() {
        if (isFirstOperateToday()) {
            try {
                OperateLogDTO operateLog = new OperateLogDTO();
                String osName = System.getProperty("os.name");
                operateLog.setServerSystem(osName);
                operateLog.setUserCode(MachineCodeUtil.generateMachineCode());
                operateLog.setUseRange("windows");
                operateLog.setSystemVersion(osName);
                operateLog.setSoftwareVersion(System.getProperty(AssistantConstants.APP_VERSION));
                operateLog.setServerSystem(SERVER_SYSTEM);
                String requestStr = JSONUtil.toJsonStr(operateLog);
                logger.info("首次操作日志上传-接口请求：{}", requestStr);
                String responseStr = sendToKhgj(requestStr, OPERATE_LOG_URL);
                logger.info("首次操作日志上传-接口响应：{}", responseStr);
            } catch (Exception e) {
                logger.error("首次操作日志上传-接口异常", e);
            }
        }
    }

    private static boolean isFirstOperateToday() {
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String lastLoggedDate = PREFS.get(AssistantConstants.LAST_LOGGER_PREF, "No cached data");
        if (!lastLoggedDate.equals(today)) {
            PREFS.put(AssistantConstants.LAST_LOGGER_PREF, today);
            return true;
        }
        return false;
    }

    /**
     * 获取最新的打印组件下载地址
     */
    public static JSONObject getPluginDownloadUrl() {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("account", MachineCodeUtil.generateMachineCode());
            params.put("serverSystem", SERVER_SYSTEM);
            params.put("appSystem", "windows");
            params.put("softwareVersion", System.getProperty(AssistantConstants.APP_VERSION));
            String requestStr = JSONUtil.toJsonStr(params);
            logger.info("打印组件下载地址-接口请求：{}", requestStr);
            String responseStr = sendToKhgj(requestStr, PLUGIN_INSTALL_URL);
            logger.info("打印组件下载地址-接口响应：{}", responseStr);
            if (!StringUtils.isEmpty(responseStr)) {
                JSONObject responseJson = JSONUtil.parseObj(responseStr);
                return responseJson.getJSONObject("data");
            }
            return null;
        } catch (Exception e) {
            logger.info("打印组件下载地址-接口异常：" + e.getMessage());
            return null;
        }
    }

    private static String sendToKhgj(String jsonStr, String requetUrl) throws Exception {
        String sign = SecureUtil.md5(jsonStr + SECRET_KEY);
        Map<String, String> headers = new HashMap<>();
        headers.put("sign", sign);
        return HttpRequestUtil.sendPostRequest(requetUrl, jsonStr, headers);
    }

}
